package com.financial.sys.service.repayment.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.financial.model.pojo.*;
import com.financial.sys.mapper.repayment.*;
import com.financial.sys.service.repayment.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.financial.sys.vo.repayment.*;
import com.financial.common.vo.JsonResult;
import com.financial.common.vo.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hzy
 * @since 2020-02-12
 */
@Service
public class TRepaymentServiceImpl extends ServiceImpl<TRepaymentMapper, TRepayment> implements TRepaymentService {

    @Autowired
    TRepaymentMapper TRepaymentMapper;
    @Autowired
    TUserWalletMapper TUserWalletMapper;
    @Autowired
    TBorrowService TBorrowService;
    @Autowired
    TUserWalletService TUserWalletService;
    @Autowired
    TAccountFlowService TAccountFlowService;
    @Autowired
    TBidService TBidService;
    @Autowired
    TRepaymentDetailService TRepaymentDetailService;
    @Autowired
    TRepaymentDetailMapper TRepaymentDetailMapper;
    @Autowired
    TBidMapper TBidMapper;

    @Override
    public List<TRepayment> selectByDeadline(Date today) {
        QueryWrapper<TRepayment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deadline",today);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public IPage query(TRepaymentQuery TRepaymentQuery) {
        if (TRepaymentQuery == null) {
            TRepaymentQuery = new TRepaymentQuery();
        }
        //判断是否是当前页
        if (TRepaymentQuery.getCurrentPage() == null) {
            TRepaymentQuery.setCurrentPage(1);
        }
        Integer currPage = TRepaymentQuery.getCurrentPage();
        Page<TRepayment> page = new Page<>(currPage, 5);

        //查询条件筛选
        String endDate = TRepaymentQuery.getEndDate();
        String beginDate = TRepaymentQuery.getBeginDate();
        String userId = TRepaymentQuery.getUserId();
        Integer status = TRepaymentQuery.getState();
        QueryWrapper<TRepayment> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(status)) {
            //判断是不是查询全部
            if (status != -1) {
                queryWrapper.eq("state", status);
            }
        }
        if (!StringUtils.isEmpty(userId)) {
            queryWrapper.eq("borrow_user_id", userId);
        }
        if (!StringUtils.isEmpty(beginDate)) {
            queryWrapper.ge("deadline", beginDate);
        }
        if (!StringUtils.isEmpty(endDate)) {
            queryWrapper.le("deadline", endDate);
        }
        IPage<TRepayment> TRepaymentQuerys = TRepaymentMapper.selectPage(page, queryWrapper);
        return TRepaymentQuerys;
    }

    @Override
    public JsonResult repay(TRepaymentrepayQuery TRepaymentrepayQuery) {
        JsonResult jsonResult = new JsonResult();
        //查出账户钱包信息
        TUserWallet tUserWallet = TUserWalletService.TUserWalletById(TRepaymentrepayQuery.getUserId());
        QueryWrapper<TRepayment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",TRepaymentrepayQuery.getId());
        queryWrapper.eq("borrow_user_id",TRepaymentrepayQuery.getUserId());
        //根据userid 和 id 查出选择还款的一条信息
        TRepayment tRepayment = TRepaymentMapper.selectOne(queryWrapper);
        //余额大于还款本期应还金额时
        if (tUserWallet.getAvailableAmount()>tRepayment.getTotalAmount()){
            System.out.println("有钱");
            Date today = new Date();
            //根据系统当前时间，判定本次还款是否逾期，并且变更还款状态为'已还'或'逾期已还'
           int res = tRepayment.getDeadline().compareTo(today);
            TRepayQuery cc = new TRepayQuery();
            TRwalletQuery wall = new TRwalletQuery();
           if (res==1){
               System.out.println("逾期已还");
               cc.setRepaymentTime(new Date());
               cc.setId(tRepayment.getId());
               cc.setState(3);
               TRepaymentMapper.updateState(cc);
           }else{
               System.out.println("逾期已还");
               cc.setRepaymentTime(new Date());
               cc.setId(tRepayment.getId());
               cc.setState(4);
               TRepaymentMapper.updateState(cc);
           }
            wall.setAvailableAmount(tUserWallet.getAvailableAmount()-tRepayment.getTotalAmount());
            wall.setResidualCreditLine(tUserWallet.getResidualCreditLine()+tRepayment.getPrincipal());
            wall.setId(TRepaymentrepayQuery.getUserId());
            TUserWalletMapper.updateResidualCreditLine(wall);

            // 并生成一条还款流水
            TAccountFlow acFlow = new TAccountFlow();
            acFlow.setAccountId(TRepaymentrepayQuery.getUserId());
            acFlow.setAmount(tRepayment.getTotalAmount());
            acFlow.setFlowType(30);
            acFlow.setAvailableAmount(tUserWallet.getAvailableAmount()-tRepayment.getPrincipal());
            acFlow.setFreezeAmount(0L);
            // 还款金额计算  （单位  元）
            BigDecimal Amount = BigDecimal.valueOf(tRepayment.getTotalAmount()/100);
            //还款说明
            acFlow.setRemark("您的--" + tRepayment.getBorrowTitle() + "--已还清，还款金额：" + Amount + "元");
            // 还款流水数据新增
            System.out.println("还款流水生成---->");
            TAccountFlowService.add(acFlow);
            System.out.println("---------->");
            /**
             * 然后会对本次还款计划的相关投资人进行收益更新，并且会为每位投资人生成1条收款记录和回款流水
             */
            //先查出 t_repayment_detail表数据  再取出 投资人ID 根据 投资人ID 进行业务的操作
            List<TRepaymentDetail> tRepaymentDetails = TRepaymentDetailService.selectByBorrowUserId(tRepayment.getBorrowUserId());
            for( TRepaymentDetail repaymentDetail : tRepaymentDetails ) {
                // 获取投资人钱包信息
                TUserWallet TUserWallet = TUserWalletMapper.selectById(repaymentDetail.getBidUserId());
                System.out.println("正在获取获取投资人钱包信息------>");
                System.out.println(TUserWallet);
                // 增加投资人可用余额
                System.out.println("投资人之前可用余额=="+repaymentDetail.getTotalAmount());
                Long bidUserAmount = TUserWallet.getAvailableAmount() + repaymentDetail.getTotalAmount();
                TUserWallet.setAvailableAmount(bidUserAmount);
                System.out.println("增加投资人可用余额新增后=="+bidUserAmount);
                // 减少投资人待收利息
                Long InterestPending = TUserWallet.getInterestPending() - repaymentDetail.getInterest();
                TUserWallet.setInterestPending(InterestPending);

                // 减少投资人待收本金
                Long PrincipalPending = TUserWallet.getPrincipalPending() - repaymentDetail.getPrincipal();
                TUserWallet.setPrincipalPending(PrincipalPending);
                // 更新投资人钱包信息
                TUserWalletService.updateByPrimaryKey(TUserWallet);
                // 生成1条回款流水
                TAccountFlow bidUserAccountFlow = new TAccountFlow();
                bidUserAccountFlow.setAccountId(TUserWallet.getAccountId());
                bidUserAccountFlow.setAmount(repaymentDetail.getTotalAmount());
                bidUserAccountFlow.setFlowType(41);
                bidUserAccountFlow.setAvailableAmount(bidUserAmount);
                bidUserAccountFlow.setFreezeAmount(TUserWallet.getFreezeAmount());

                // 回款金额
                BigDecimal returnAmount = BigDecimal.valueOf(repaymentDetail.getTotalAmount()/100);
                bidUserAccountFlow.setRemark("回款--" + repaymentDetail.getBorrowTitle() + "--成功，回款金额：" + returnAmount + "元");
                // 插入回款流水
                this.TAccountFlowService.add(bidUserAccountFlow);
                System.out.println("插入回款流水成功");
                // 更新'还款明细'中的还款时间
                repaymentDetail.setRepaymentTime(new Date());
                TRepaymentDetailMapper.updateById(repaymentDetail);
                System.out.println("更新成功");
            }
            //如果本次还款之后，该借款标的所有贷款全部还完  就更新该借款标的状态为'已完成'
             //通过借款ID找到 相关借款数据
            List<TRepayment> repaymentList = selectBorrowId(tRepayment.getBorrowId());
            System.out.println(repaymentList+"====>");
            //判断查出的借款状态
            int overdue=0;
            int found = 0;
            for( TRepayment tmpRepayment : repaymentList ) {
                // 逾期未还款
                if( tmpRepayment.getState() == 1 ) {
                    found = 2;
                    overdue = 2;
                }
                // 未还款
                if( tmpRepayment.getState() == 2 ) {
                    found = 2;
                }
                // 逾期已还
                if( tmpRepayment.getState() == 4) {
                    overdue = 2;
                }
            }
            // 如果没有找到未还款，就更新借款信息的状态为 '已完成'
            if( found == 0 ) {
                // 查询借款信息
                TBorrow borrow = TBorrowService.selectBorrowId(tRepayment.getBorrowId());
                // 更新借款人状态  '已还'
                borrow.setBorrowState(50);
                //保存 借款人状态
                TBorrowService.updateBorrow(borrow);
                // 根据借款ID 更新标的 状态 为 ‘已还’
                TBid bid = new TBid();
                bid.setBorrowId(tRepayment.getBorrowId());
                bid.setBorrowState(50);
                TBidMapper.updateById(bid);
                //1. 如果没有存在逾期的还款，增加用户的信用分额度 +10   同时增加授信额度 和 剩余授信额度
                    if( overdue == 2 ) {
                     //信用得分
                    int NewCreditScore = tUserWallet.getCreditScore()+10;
                    tUserWallet.setCreditScore(NewCreditScore);
                    //授信额度
                    long creditLine = NewCreditScore * 100 * 100;
                    tUserWallet.setCreditLine(creditLine);
                    //  剩余授信额度新增
                    long rewardCreditLine = 10 * 100;
                    tUserWallet.setResidualCreditLine(tUserWallet.getResidualCreditLine() + rewardCreditLine);
                    //更新用户余额信息
                    TUserWalletService.updateByPrimaryKey(tUserWallet);
                    System.out.println("更新成功");
                }
        }
 }else{
            jsonResult.setCode(ResponseCode.FAILED);
            jsonResult.setMsg("余额不足");
        }
return jsonResult;
}
    @Override
    public List<TRepayment> selectBorrowId(String borrowId) {
        QueryWrapper<TRepayment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("borrow_id",borrowId);
        return baseMapper.selectList(queryWrapper);
    }
}
